package cn.lingyangwl.agile.gateway.service;

import cn.lingyangwl.agile.gateway.body.*;
import cn.lingyangwl.agile.gateway.constants.*;
import cn.lingyangwl.agile.gateway.model.*;
import cn.lingyangwl.agile.gateway.remote.*;
import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.framework.cache.core.service.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
public class AccessKeyService {
    @Resource
    private CacheService cacheService;
    @Resource
    private SystemApi systemApi;

    @Resource(name = "myThreadPool")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public AccessKeyResp getAccessKeyBySecretId(String secretId, GatewayContext context) {
        AccessKeyResp accessKeyResp = null;
        try {
            String cacheKey = String.format(CacheCons.ACCESS_KEY, secretId);
            Object obj = cacheService.opsForValue().get(cacheKey);
            if (Objects.isNull(obj)) {
                accessKeyResp = systemApi.getAccessKeyBySecretId(secretId).get();
                if (Objects.isNull(accessKeyResp)) {
                    return null;
                }
                cacheService.opsForValue().setEx(cacheKey, JSON.toJSONString(accessKeyResp), 6, TimeUnit.HOURS);
            } else {
                accessKeyResp = JSON.parseObject(String.valueOf(obj), AccessKeyResp.class);
            }
            return accessKeyResp;

        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            log.error("调用accessKeyApi失败, ", e);
            throw new BizException("远程服务调用失败");
        } finally {
            if (Objects.nonNull(accessKeyResp)) {
                context.addRequestHeader(RequestCons.Headers.ACCESS_SECRET_ID, accessKeyResp.getSecretId());
                context.addRequestHeader(RequestCons.Headers.ACCESS_SECRET_KEY, accessKeyResp.getSecretKey());
            }
        }
    }
}
